package com.java1412.lb;

import org.springframework.beans.propertyeditors.CurrencyEditor;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author java1412
 * @create 2022-09-01 16:17
 */
@Component
public class MyLB implements ILoadBalancer {

    // 新建原子整型类
    private AtomicInteger atomicInteger = new AtomicInteger(0);

    public final int getAndIncrement() {
        int current; // 当前下标
        int next; // 下一个服务实例的下标
        do {
            // 获取当前的下标
            current = this.atomicInteger.get();
            // current不能整型最大值，如果是最大值就从0开始，否则加1
            next = current >= Integer.MAX_VALUE ? 0 : current + 1;
        } while (!this.atomicInteger.compareAndSet(current, next));
        System.out.println("******第几次访问，次数next : " + next);
        // 下一个服务实例的下标
        return next;
    }

    @Override
    public ServiceInstance instances(List<ServiceInstance> serviceInstances) {
        // 对服务实例进行非空
        if (serviceInstances.size() <= 0) {
            return null;
        }
        int index = getAndIncrement() % serviceInstances.size();
        return serviceInstances.get(index);
    }
}
